package com.emm.yixun.common.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class HttpUtil {

    private static Logger logger = LoggerFactory.getLogger(HttpUtil.class);
    public static String doPost(String url, Map<String, String> params, String charset) {
        StringBuffer response = new StringBuffer();  
        HttpClient client = new HttpClient();  
        PostMethod method = new PostMethod(url);  
        // 设置Http Post数据  
        method.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=" + charset);  
        if(params != null){  
            Set<String> keySet = params.keySet();  
            NameValuePair[] param = new NameValuePair[keySet.size()];  
            int i = 0;  
            for(String key : keySet){  
                param[i] = new NameValuePair(key, params.get(key));  
                i++;  
            }  
            method.setRequestBody(param);  
        }  
        InputStream responseBodyStream = null;  
        InputStreamReader streamReader = null;  
        BufferedReader reader = null;  
        try {  
            client.executeMethod(method);  
            if (method.getStatusCode() == HttpStatus.SC_OK) {  
                responseBodyStream = method.getResponseBodyAsStream();  
                streamReader = new InputStreamReader(responseBodyStream, charset);  
                reader = new BufferedReader(streamReader);  
                String line;  
                while ((line = reader.readLine()) != null) {  
                    response.append(line);  
                }  
            }  
        } catch (IOException e) {  
            logger.error("执行HTTP Post请求" + url + "时，发生异常！", e);  
        } finally {  
            try {  
                responseBodyStream.close();  
                streamReader.close();  
                reader.close();  
            } catch (IOException e) {  
                logger.error("执行HTTP Post请求" + url + "时，发生异常，关闭流异常！", e);  
                e.printStackTrace();  
            }  
            method.releaseConnection();  
        }  
        return response.toString();  
    }

    /**
     * 调用非固定地址
     *
     * @param url 接口url
     * @param data //json入参
     * @return json
     */
    public static String doPostUrl(String url, JSONObject data, String charset) {
        String result = null;
        org.apache.http.client.HttpClient client = HttpClientBuilder.create().build();
        HttpPost httpPost = null;
        try {
            httpPost = new HttpPost(url);
            httpPost.setHeader("Content-Type", "application/json;charset=" + charset);
            StringEntity entity = new StringEntity(JSONObject.toJSONString(data), charset);
            entity.setContentEncoding(charset);
            entity.setContentType("application/json");
            httpPost.setEntity(entity);
            HttpResponse response = client.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, charset);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    
    public static String doPostByString(String url, String content, String charset){
    	String result = "";
    	HttpPost httpPost = new HttpPost(url);
    	CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        try {
	   	StringEntity entity = new StringEntity(content,charset);
	   	entity.setContentEncoding(charset);
	        entity.setContentType("application/json");
	        httpPost.setEntity(entity);
	        HttpResponse httpResult = httpClient.execute(httpPost);
	        int statusCode = httpResult.getStatusLine().getStatusCode();
	        if (statusCode == HttpStatus.SC_OK) {
	        	result = EntityUtils.toString(httpResult.getEntity(),charset);
	        }
	        httpClient.close();
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return result;
    } 
    
    
    public static void main(String[] args) {
	Map<String, String> map = new HashMap<String, String>();
	map.put("ticket", "504dbf2973054965a8b09bac0237a589");
	String result = doPost("http://oa.gteast.cn:8088/wxthirdapi/getUserInfoByTicket", map, "UTF-8");
	System.out.println(result);
    }
}
